# -*- coding: utf-8 -*-
from kubernetes import client, config
from kubernetes.watch import Watch
from kubernetes.client import CoreV1Api
import kubernetes
from kubernetes.client.api_client import ApiClient
from kubernetes.client.rest import ApiException
import json

from numpy import cumsum


class CrdApiInfo(CoreV1Api):
    def list_namespaced_pod_with_http_info(self, namespace, url=None, **kwargs):
  
            
        
        path_params = {
            "namespace":  namespace
        }

        query_params = [
            # ('labelSelector', 'app=memcached'),
            ('watch', True)
        ]

        print("非自定义: %s" % url)

        return self.api_client.call_api(url,
                                        'GET',
                                        path_params,
                                        query_params,
                                        _return_http_data_only=True,
                                        _preload_content=False,
                                        )


class Controllers:

    def __init__(self, kube_config, NAME, CRD_GROUP=None, CRD_PLURAL=None, CRD_VERSION=None, CRD_NAMESPACE=None, Cumsum=False, url=None):
        self.kube_config = kube_config
        self.NAME = NAME
        self.CRD_GROUP = CRD_GROUP
        self.CRD_VERSION = CRD_VERSION
        self.CRD_PLURAL = CRD_PLURAL
        self.ApiException = ApiException
        self.client = client
        self.Configuration = kubernetes.client.Configuration()
        self.CRD_NAMESPACE = CRD_NAMESPACE
        self.DEBUG = True
        self.url = url
        self.Cumsum = Cumsum

    def load_config(self):
        if self.DEBUG == True:
            config.kube_config.load_kube_config(config_file=self.kube_config)

        else:
            kubernetes.config.load_incluster_config()

    def Update(self, event):
        print("更新 %s" % (self.NAME))

    def Delete(self, event):

        print("删除 %s" % (self.NAME))

    def Create(self, event):

        print("创建 %s" % (self.NAME))

    def WatchDo(self):
        print ("========启动控制器%s======" % self.NAME)
        self.load_config()

        w = Watch()
        c = CrdApiInfo()
        if self.Cumsum == True:
                self.url = '/apis/%s/%s/namespaces/%s/%s' % (
                self.CRD_GROUP, self.CRD_VERSION, self.CRD_NAMESPACE, self.CRD_PLURAL)
                print("自定义: %s" % self.url)

        for event in w.stream(
            c.list_namespaced_pod_with_http_info,
            namespace=self.CRD_NAMESPACE,
            url=self.url,
            
        ):

            if "MODIFIED" in event["type"]:
                self.Update(event)
            elif "DELETED" in event["type"]:
                self.Delete(event)

            elif "ADDED" in event["type"]:
                self.Create(event)
